﻿using System;
using System.Collections.Generic;
using System.Text;
using reactiveBT.Utilities;

namespace reactiveBT.BT
{
    /// <summary>
    /// 条件循环分支节点，接受无参，返回一个bool值的函数fn作为构造参数
    /// 每次Tick前均会验证函数func的返回值，为真时返回Continue，否则返回Failure
    /// 向上传递Abort信息
    /// 已经测试
    /// </summary>
    public class While : Branch
    {
        System.Func<bool> fn;
        public While(System.Func<bool> fn)
        {
            this.fn = fn;
        }
        public override BTState Tick(int BTid)
        {
            if(needToReset)
            {
                base.ResetSelf();
                base.ResetChildren();
                needToReset = false;
            }
            if(fn())
            {
                var result = base.Tick(BTid);
                switch(result)
                {
                    case BTState.Abort:
                        needToReset = true;
                        return BTState.Abort;
                    case BTState.Success:
                        base.ResetSelf();
                        base.ResetChildren();
                        return BTState.Continue;
                    default:
                        return result;
                }
                //impossible
                throw new System.Exception("never happen");
            }
            else
            {
                needToReset = true;
                return BTState.Failure;
            }
        }
    }
}
